package com.zz.nondatain.base;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 所有ViewModel的基类，处理共有的逻辑
 */
public abstract class BaseViewModel extends ViewModel {
    
    // 管理RxJava订阅
    private CompositeDisposable compositeDisposable;
    
    // 加载状态
    private final MutableLiveData<Boolean> _loading = new MutableLiveData<>(false);
    public LiveData<Boolean> loading = _loading;
    
    // 错误信息
    private final MutableLiveData<String> _error = new MutableLiveData<>();
    public LiveData<String> error = _error;
    
    /**
     * 添加Disposable到CompositeDisposable
     */
    protected void addDisposable(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }
    
    /**
     * 设置加载状态
     */
    protected void setLoading(boolean loading) {
        _loading.postValue(loading);
    }
    
    /**
     * 设置错误信息
     */
    protected void setError(String errorMsg) {
        _error.postValue(errorMsg);
    }
    
    @Override
    protected void onCleared() {
        super.onCleared();
        if (compositeDisposable != null) {
            compositeDisposable.clear();
            compositeDisposable = null;
        }
    }
} 